import "dotenv/config";
import { Provider } from "../src/core/provider";
import { Wallet } from "../src/core/wallet";
import { parseEther, formatEther } from "../src/core/utils";

function requireEnv(name: string): string {
  const v = process.env[name];
  if (!v || !v.trim()) throw new Error(`缺少环境变量: ${name}`);
  return v.trim();
}

async function main() {
  console.log("=== TS版：手写核心完成 Sepolia 转账 ===");
  const RPC_URL = requireEnv("RPC_URL");
  const PRIVATE_KEY = requireEnv("PRIVATE_KEY");
  const TO = requireEnv("TO_ADDRESS");
  const AMOUNT = (process.env["AMOUNT_ETH"] || "0.001").trim();

  const provider = new Provider(RPC_URL);
  const wallet = new Wallet(PRIVATE_KEY as `0x${string}`, provider);

  const chain = await provider.chainId();
  console.log(`连接网络 chainId=${chain}`);
  console.log(`付款地址: ${wallet.address}`);
  const balSender = await provider.balance(wallet.address);
  console.log(`付款地址余额: ${formatEther(balSender)} ETH`);
  const balBefore = await provider.balance(TO);
  console.log(`收款地址初始余额: ${formatEther(balBefore)} ETH`);

  const valueWei = parseEther(AMOUNT);
  console.log("发送交易... (EIP-1559)");
  const txHash = await wallet.sendEip1559(TO as `0x${string}`, valueWei);
  console.log(`交易已提交: ${txHash}`);
  console.log(`Etherscan: https://sepolia.etherscan.io/tx/${txHash}`);

  console.log("等待上链确认...");
  for (let i = 0; i < 60; i++) {
    const rc = await provider.getTransactionReceipt(txHash);
    if (rc) {
      const status = Number(BigInt(rc.status));
      const block = Number(BigInt(rc.blockNumber));
      console.log(`状态: ${status === 1 ? "成功" : "失败"} 区块: ${block}`);
      break;
    }
    await new Promise((r) => setTimeout(r, 2000));
  }

  const balAfter = await provider.balance(TO);
  console.log(`收款地址余额增量: +${formatEther(balAfter - balBefore)} ETH`);
  console.log("完成。你已用TS手写核心成功完成一次Sepolia转账！");
}

main().catch((e) => {
  console.error("执行失败:", e);
  process.exit(1);
});